/**
 * Filename: InviteChooseActivity.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/3 15:09
 */
package com.github.postsanf.yinian.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.bean.YNAlbum;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.YNInviteSecret;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMMin;

import org.json.JSONObject;

import java.util.LinkedHashMap;


public class InviteChooseActivity extends BaseActivity implements View.OnClickListener {
    private LinearLayout ib_wx_invite;
    private LinearLayout ib_wx_min;
    private SimpleDraweeView invite_choose_face;
    private LinearLayout ib_code_saoyisao;
    private String inviteKey;
    private String inviteUrl;
    private String title;
    private YNAlbum curAlbum;
    private ImageView iv_back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_invite_choose);
        curAlbum = YNSingleton.getInstance().getCurAlbum();
        doInvateKey();
        initView();
    }

    private void doInvateKey() {
        String invite = CommonConstants.YNS_USER_ID + "=" + application.getCurID() + "," + CommonConstants.YNS_GROUP_ID + "=" + curAlbum.getGroupid();
        try {
            inviteKey = YNInviteSecret.encryptDES(invite, getString(R.string.UNKNOW_ID));
        } catch (Exception e) {
            e.printStackTrace();
        }
        inviteUrl = getString(R.string.NET_INVITE_WX) + inviteKey;
    }

    private void initView() {
        title = application.getCurUser().getUnickname() + "和你分享了一段时光";
        ib_wx_invite = (LinearLayout) findViewById(R.id.ib_wx_invite);
        ib_wx_min = (LinearLayout) findViewById(R.id.ib_wx_min);
        invite_choose_face = (SimpleDraweeView) findViewById(R.id.invite_choose_face);
        ib_code_saoyisao = (LinearLayout) findViewById(R.id.ib_code_saoyisao);
        iv_back = ((ImageView) findViewById(R.id.iv_back));
        iv_back.setOnClickListener(this);
//        ib_code_invite.setOnClickListener(this);
        ib_wx_invite.setOnClickListener(this);
        ib_wx_min.setOnClickListener(this);
        ib_code_saoyisao.setOnClickListener(this);
        String urls = (curAlbum == null || curAlbum.getGpic() == null) ? "" : curAlbum.getGpic();
        Uri uri = Uri.parse(urls);
        ImageOptHelper.showFrescoBlur(uri, invite_choose_face, InviteChooseActivity.this);
    }


    String desc = "这里面有几张我很喜欢的照片，快来看看你喜欢嘛？";

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.ib_wx_invite:
//                ShareUtils.onInvateFromWx(application.getWxApi(), this, inviteUrl, title, desc);
//                Intent statintent = new Intent(ACTIONs.record);
//                statintent.putExtra("key", "邀请好友（微信邀请）_5");
//                statintent.putExtra("value", 1);
//                sendBroadcast(statintent);
//                break;
//            case R.id.ib_code_invite:
//                intent2Activity(InviteCodectivity.class);
//                Intent codeintent = new Intent(ACTIONs.record);
//                codeintent.putExtra("key", "邀请好友（邀请码）_5");
//                codeintent.putExtra("value", 1);
//                sendBroadcast(codeintent);
//                break;
            case R.id.ib_code_saoyisao:
                Intent erweimaintent = new Intent(InviteChooseActivity.this, InviteErWeiMaActivity.class);
                erweimaintent.putExtra("inviteUrl", inviteUrl);
                startActivity(erweimaintent);
                Intent saointent = new Intent(ACTIONs.record);
                saointent.putExtra("key", "邀请好友（二维码）_5");
                saointent.putExtra("value", 1);
                sendBroadcast(saointent);
                break;
            case R.id.ib_wx_min:
                UMMin umMin = new UMMin(inviteUrl);
                umMin.setThumb(new UMImage(InviteChooseActivity.this, R.drawable.invite_wxminshare));
                umMin.setTitle(title);
                umMin.setDescription(desc);
                umMin.setPath("pages/viewscoll/viewscoll?groupid=" + application.getCurGid() + "&from=grouplist"
                        + "&fromUserID=" + application.getCurID()
                        + "&fromSpaceID=" + application.getCurGid()
                        + "&port=App邀请新成员");
                umMin.setUserName("gh_11ddcc4aabbb");
                new ShareAction(InviteChooseActivity.this)
                        .withMedia(umMin)
                        .setPlatform(SHARE_MEDIA.WEIXIN)
                        .setCallback(umShareListener).share();
//                ShareUtils.sendMiniApps(application.getWxApi(),this, title, desc, inviteUrl, application.getCurGid());
                break;
            case R.id.iv_back:
                finish();
                break;

        }
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                Toast.makeText(InviteChooseActivity.this, platform + " 收藏成功啦", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(InviteChooseActivity.this, platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
                inviteSucess();
                finish();
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(InviteChooseActivity.this, platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (t != null) {
                Log.d("throw", "throw:" + t.getMessage());
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(InviteChooseActivity.this, platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };

    private void inviteSucess() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        StringRequest req = new StringRequest("https://api.zhuiyinanian.com/YinianProject/yinian/ModifyUserInviteSign")
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        try {
                            JSONObject json = new JSONObject(s);
                            if (ReqUtils.isSuccess(json.optString("code"))) {

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(getString(R.string.YN_NET_LINK));
                    }
                });
        liteHttp.executeAsync(req);
    }


    private long fristTime;

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
        fristTime = System.currentTimeMillis();
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
        Intent intent = new Intent(ACTIONs.record);
        intent.putExtra("key", "invite_3");
        intent.putExtra("value", new Long(System.currentTimeMillis() - fristTime).intValue());
        sendBroadcast(intent);
    }
}



